aboutsummaryrefslogtreecommitdiff
path: root/pages/en/anime/watch/[...info].js
blob: f5b4fce7ee8e414ff73e3196b67195988d9ba2e1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import React, { useEffect, useRef, useState } from "react";
import PlayerComponent from "@/components/watch/player/playerComponent";
import { FlagIcon, ShareIcon } from "@heroicons/react/24/solid";
import Details from "@/components/watch/primary/details";
import EpisodeLists from "@/components/watch/secondary/episodeLists";
import { getServerSession } from "next-auth";
import { useWatchProvider } from "@/lib/hooks/watchPageProvider";
import { authOptions } from "../../../api/auth/[...nextauth]";
import { createList, createUser, getEpisode } from "@/prisma/user";
import Link from "next/link";
import MobileNav from "@/components/shared/MobileNav";
import { NewNavbar } from "@/components/shared/NavBar";
import Modal from "@/components/modal";
import AniList from "@/components/media/aniList";
import { signIn } from "next-auth/react";
import BugReportForm from "@/components/shared/bugReport";
import Skeleton from "react-loading-skeleton";
import Head from "next/head";

export async function getServerSideProps(context) {
  let userData = null;
  const session = await getServerSession(context.req, context.res, authOptions);
  const accessToken = session?.user?.token || null;

  const query = context?.query;
  if (!query) {
    return {
      notFound: true,
    };
  }

  const proxy = process.env.PROXY_URI;
  const disqus = process.env.DISQUS_SHORTNAME;

  const [aniId, provider] = query?.info;
  const watchId = query?.id;
  const epiNumber = query?.num;
  const dub = query?.dub;

  const ress = await fetch(`https://graphql.anilist.co`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(accessToken && { Authorization: `Bearer ${accessToken}` }),
    },
    body: JSON.stringify({
      query: `query ($id: Int) {
              Media (id: $id) {
                mediaListEntry {
                  progress
                  status
                  customLists
                  repeat
                }
                id
                idMal
                title {
                  romaji
                  english
                  native
                }
                status
                genres
                episodes
                studios {
                  edges {
                    node {
                      id
                      name
                    }
                  }
                }
                bannerImage
                description
                coverImage {
                  extraLarge
                  color
                }
                synonyms
                  
              }
            }
          `,
      variables: {
        id: aniId,
      },
    }),
  });
  const data = await ress.json();

  try {
    if (session) {
      await createUser(session.user.name);
      await createList(session.user.name, watchId);
      const data = await getEpisode(session.user.name, watchId);
      userData = JSON.parse(
        JSON.stringify(data, (key, value) => {
          if (key === "createdDate") {
            return String(value);
          }
          return value;
        })
      );
    }
  } catch (error) {
    console.error(error);
    // Handle the error here
  }
  return {
    props: {
      sessions: session,
      provider: provider || null,
      watchId: watchId || null,
      epiNumber: epiNumber || null,
      dub: dub || null,
      userData: userData?.[0] || null,
      info: data.data.Media || null,
      proxy,
      disqus,
    },
  };
}

export default function Watch({
  info,
  watchId,
  disqus,
  proxy,
  dub,
  userData,
  sessions,
  provider,
  epiNumber,
}) {
  const [artStorage, setArtStorage] = useState(null);

  const [episodeNavigation, setEpisodeNavigation] = useState(null);
  const [episodesList, setepisodesList] = useState();
  const [mapEpisode, setMapEpisode] = useState(null);

  const [episodeSource, setEpisodeSource] = useState(null);

  const [open, setOpen] = useState(false);
  const [isOpen, setIsOpen] = useState(false);

  const [onList, setOnList] = useState(false);

  const { theaterMode, setPlayerState, setAutoPlay, setMarked } =
    useWatchProvider();

  const playerRef = useRef(null);

  useEffect(() => {
    async function getInfo() {
      if (info.mediaListEntry) {
        setOnList(true);
      }

      const response = await fetch(
        `/api/v2/episode/${info.id}?releasing=${
          info.status === "RELEASING" ? "true" : "false"
        }${dub ? "&dub=true" : ""}`
      ).then((res) => res.json());
      const getMap = response.find((i) => i?.map === true) || response[0];
      let episodes = response;

      if (getMap) {
        if (provider === "gogoanime" && !watchId.startsWith("/")) {
          episodes = episodes.filter((i) => {
            if (i?.providerId === "gogoanime" && i?.map !== true) {
              return null;
            }
            return i;
          });
        }

        setMapEpisode(getMap?.episodes);
      }

      if (episodes) {
        const getProvider = episodes?.find((i) => i.providerId === provider);
        const episodeList = dub
          ? getProvider?.episodes?.filter((x) => x.hasDub === true)
          : getProvider?.episodes.slice(0, getMap?.episodes.length);
        const playingData = getMap?.episodes.find(
          (i) => i.number === Number(epiNumber)
        );

        if (getProvider) {
          setepisodesList(episodeList);
          const currentEpisode = episodeList?.find(
            (i) => i.number === parseInt(epiNumber)
          );
          const nextEpisode = episodeList?.find(
            (i) => i.number === parseInt(epiNumber) + 1
          );
          const previousEpisode = episodeList?.find(
            (i) => i.number === parseInt(epiNumber) - 1
          );
          setEpisodeNavigation({
            prev: previousEpisode,
            playing: {
              id: currentEpisode.id,
              title: playingData?.title,
              description: playingData?.description,
              img: playingData?.img || playingData?.image,
              number: currentEpisode.number,
            },
            next: nextEpisode,
          });
        }
      }

      setArtStorage(JSON.parse(localStorage.getItem("artplayer_settings")));
      // setEpiData(episodes);
    }
    getInfo();

    return () => {
      setEpisodeNavigation(null);
    };
  }, [sessions?.user?.name, epiNumber, dub]);

  useEffect(() => {
    async function fetchData() {
      if (info) {
        const autoplay =
          localStorage.getItem("autoplay_video") === "true" ? true : false;
        setAutoPlay(autoplay);

        const anify = await fetch("/api/v2/source", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            source:
              provider === "gogoanime" && !watchId.startsWith("/")
                ? "consumet"
                : "anify",
            providerId: provider,
            watchId: watchId,
            episode: epiNumber,
            id: info.id,
            sub: dub ? "dub" : "sub",
          }),
        }).then((res) => res.json());

        const skip = await fetch(
          `https://api.aniskip.com/v2/skip-times/${info.idMal}/${parseInt(
            epiNumber
          )}?types[]=ed&types[]=mixed-ed&types[]=mixed-op&types[]=op&types[]=recap&episodeLength=`
        ).then((res) => {
          if (!res.ok) {
            switch (res.status) {
              case 404: {
                return null;
              }
            }
          }
          return res.json();
        });

        const op =
          skip?.results?.find((item) => item.skipType === "op") || null;
        const ed =
          skip?.results?.find((item) => item.skipType === "ed") || null;

        const episode = {
          epiData: anify,
          skip: {
            op,
            ed,
          },
        };

        setEpisodeSource(episode);
      }
    }

    fetchData();
    return () => {
      setEpisodeSource();
      setPlayerState({
        currentTime: 0,
        isPlaying: false,
      });
      setMarked(0);
    };
  }, [provider, watchId, info?.id]);

  const handleShareClick = async () => {
    try {
      if (navigator.share) {
        await navigator.share({
          title: `Watch Now - ${info?.title?.english || info.title.romaji}`,
          // text: `Watch [${info?.title?.romaji}] and more on Moopa. Join us for endless anime entertainment"`,
          url: window.location.href,
        });
      } else {
        // Web Share API is not supported, provide a fallback or show a message
        alert("Web Share API is not supported in this browser.");
      }
    } catch (error) {
      console.error("Error sharing:", error);
    }
  };

  function handleOpen() {
    setOpen(true);
    document.body.style.overflow = "hidden";
  }

  function handleClose() {
    setOpen(false);
    document.body.style.overflow = "auto";
  }

  return (
    <>
      <Head>
        <title>
          {episodeNavigation?.playing?.title ||
            `${info?.title?.romaji} - Episode ${epiNumber}`}
        </title>
        {/* Write the best SEO for this watch page with data of anime title from info.title.romaji, episode title from episodeNavigation?.playing?.title, description from episodeNavigation?.playing?.description, episode number from epiNumber */}
        <meta name="twitter:card" content="summary_large_image" />
        {/* Write the best SEO for this homepage */}
        <meta
          name="description"
          content={episodeNavigation?.playing?.description || info?.description}
        />
        <meta
          name="keywords"
          content="anime, anime streaming, anime streaming website, anime streaming free, anime streaming website free, anime streaming website free english subbed, anime streaming website free english dubbed, anime streaming website free english subbed and dubbed, anime streaming webs
          ite free english subbed and dubbed download, anime streaming website free english subbed and dubbed"
        />
        <meta name="robots" content="index, follow" />

        <meta property="og:type" content="website" />
        <meta property="og:url" content="https://moopa.live/" />
        <meta
          property="og:title"
          content={`Watch - ${
            episodeNavigation?.playing?.title || info?.title?.english
          }`}
        />
        <meta
          property="og:description"
          content="Discover your new favorite anime or manga title! Moopa offers a vast library of high-quality content, accessible on multiple devices and without any interruptions. Start using Moopa today!"
        />
        <meta property="og:image" content="/preview.png" />
        <meta property="og:site_name" content="Moopa" />
        <meta name="twitter:card" content="summary_large_image" />
        <meta
          name="twitter:title"
          content={`Watch - ${
            episodeNavigation?.playing?.title || info?.title?.english
          }`}
        />
        <meta
          name="twitter:description"
          content={episodeNavigation?.playing?.description || info?.description}
        />
      </Head>
      <Modal open={open} onClose={() => handleClose()}>
        {!sessions && (
          <div className="flex-center flex-col gap-5 px-10 py-5 bg-secondary rounded-md">
            <h1 className="text-md font-extrabold font-karla">
              Edit your list
            </h1>
            <button
              className="flex items-center bg-[#363642] rounded-md text-white p-1"
              onClick={() => signIn("AniListProvider")}
            >
              <h1 className="px-1 font-bold font-karla">Login with AniList</h1>
              <div className="scale-[60%] pb-[1px]">
                <AniList />
              </div>
            </button>
          </div>
        )}
      </Modal>
      <BugReportForm isOpen={isOpen} setIsOpen={setIsOpen} />
      <main className="w-screen h-full">
        <NewNavbar
          scrollP={20}
          withNav={true}
          shrink={true}
          paddingY={`py-2 ${theaterMode ? "" : "lg:py-4"}`}
        />
        <MobileNav hideProfile={true} sessions={sessions} />
        <div
          className={`mx-auto pt-16 ${theaterMode ? "lg:pt-16" : "lg:pt-20"}`}
        >
          {theaterMode && (
            <PlayerComponent
              id={"cinematic"}
              session={sessions}
              playerRef={playerRef}
              dub={dub}
              info={info}
              watchId={watchId}
              proxy={proxy}
              track={episodeNavigation}
              data={episodeSource?.epiData}
              skip={episodeSource?.skip}
              timeWatched={userData?.timeWatched}
              provider={provider}
              className="w-screen max-h-[85dvh]"
            />
          )}
          <div
            id="default"
            className={`${
              theaterMode ? "lg:max-w-[80%]" : "lg:max-w-[95%]"
            } w-full flex flex-col lg:flex-row mx-auto`}
          >
            <div id="primary" className="w-full">
              {!theaterMode && (
                <PlayerComponent
                  id={"default"}
                  session={sessions}
                  playerRef={playerRef}
                  dub={dub}
                  info={info}
                  watchId={watchId}
                  proxy={proxy}
                  track={episodeNavigation}
                  data={episodeSource?.epiData}
                  skip={episodeSource?.skip}
                  timeWatched={userData?.timeWatched}
                  provider={provider}
                />
              )}
              <div
                id="details"
                className="flex flex-col gap-5 w-full px-3 lg:px-0"
              >
                <div className="flex items-end justify-between pt-3 border-b-2 border-secondary pb-2">
                  <div className="w-[55%]">
                    <div className="flex font-outfit font-semibold text-lg lg:text-2xl text-white line-clamp-1">
                      <Link
                        href={`/en/anime/${info?.id}`}
                        className="hover:underline line-clamp-1"
                      >
                        {(episodeNavigation?.playing?.title ||
                          info.title.romaji) ??
                          "Loading..."}
                      </Link>
                    </div>
                    <p className="font-karla">
                      {episodeNavigation?.playing?.number ? (
                        `Episode ${episodeNavigation?.playing?.number}`
                      ) : (
                        <Skeleton width={120} height={16} />
                      )}
                    </p>
                  </div>
                  <div>
                    <div className="flex gap-2 text-sm">
                      <button
                        type="button"
                        onClick={handleShareClick}
                        className="flex items-center gap-2 px-3 py-1 ring-[1px] ring-white/20 rounded overflow-hidden"
                      >
                        <ShareIcon className="w-5 h-5" />
                        share
                      </button>
                      <button
                        type="button"
                        onClick={() => setIsOpen(true)}
                        className="flex items-center gap-2 px-3 py-1 ring-[1px] ring-white/20 rounded overflow-hidden"
                      >
                        <FlagIcon className="w-5 h-5" />
                        report
                      </button>
                    </div>
                  </div>
                  {/* <div>right</div> */}
                </div>

                <Details
                  info={info}
                  session={sessions}
                  description={info?.description}
                  epiNumber={epiNumber}
                  id={info}
                  onList={onList}
                  setOnList={setOnList}
                  handleOpen={() => handleOpen()}
                  disqus={disqus}
                />
              </div>
            </div>
            <div
              id="secondary"
              className={`relative ${theaterMode ? "pt-2" : ""}`}
            >
              <EpisodeLists
                info={info}
                map={mapEpisode}
                providerId={provider}
                watchId={watchId}
                episode={episodesList}
                artStorage={artStorage}
                dub={dub}
              />
            </div>
          </div>
        </div>
      </main>
    </>
  );
}